import { useMemo, useState } from "react"
import classnames from "classnames"
import dayjs from "dayjs"
import "./index.scss"
import Icon from "@/components/Icon"

import { billTypeToName } from "@/contants/billData"

const DailyBill = ({ date, billList }) => {
  function formatDate(date) {
    // 1. 移除空格和管道符
    const normalized = date.replace(/\s*\|\s*/g, '-');

    // 2. 解析为Day.js对象并格式化
    return dayjs(normalized).format('YYYY年MM月DD日');
  }
  const dayResult = useMemo(() => {
    const pay = billList.filter(item => item.type === 'pay').reduce((pre, cur) => pre + cur.money, 0)
    const income = billList.filter(item => item.type === 'income').reduce((pre, cur) => pre + cur.money, 0)
    const total = pay + income
    return { pay, income, total }
  }, [billList])

  const [visible, setVisible] = useState(false)


  return (
    <div className={classnames('dailyBill')}>
      <div className="header">
        <div className="dateIcon">
          <span className="date">{formatDate(date)}</span>
          {/* 点击实现展开/折叠,并通过visible控制类名实现箭头方向的变化 */}
          <span className={classnames('arrow', visible && 'expand')} onClick={() => setVisible(!visible)}></span>
        </div>
        <div className="oneLineOverview">
          <div className="pay">
            <span className="type">支出</span>
            <span className="money">{dayResult.pay.toFixed(2)}</span>
          </div>
          <div className="income">
            <span className="type">收入</span>
            <span className="money">{dayResult.income.toFixed(2)}</span>
          </div>
          <div className="balance">
            <span className="type">结余</span>
            <span className="money">{dayResult.total.toFixed(2)}</span>
          </div>
        </div>
      </div>
      {/* 单日列表 */}
      <div className="billList" style={{ display: visible ? "block" : "none" }}>
        {billList.map(item => {
          return (
            <div className="bill" key={item.id}>
              {/* 引入图标组件并根据props适配不同的icon */}
              <Icon type={item.useFor} />
              <div className="detail">
                <div className="billType">{billTypeToName[item.useFor]}</div>
              </div>
              <div className={classnames("money", item.type)}>
                {item.money.toFixed(2)}
              </div>
            </div>
          )
        })}
      </div>
    </div>
  )
}

export default DailyBill